// pages/detail/detail.js
import {
  getOne,
  inc,
  get,
  add
} from '../../utils/db'
Page({
  data: {
    list: {}, //菜谱名称
    imgs: [], //轮播图
    isLike: false,
    id: "",
    allow: true, //关注的操作：true 允许操作；false 不允许
  },
  async onLoad(e) {
    this.data.id = e.id;

    this.getDetail()
    //判断是否关注
    var openid = wx.getStorageSync('openid')
    var menuId = this.data.id;
    var result = await get("likes", {
      _openid: openid,
      menuId: menuId
    }).catch(err => console.log(err))
    if (result.data.length > 0) {
      //已关注
      this.setData({
        isLike: true
      })
    } else {
      //未关注
      this.setData({
        isLike: false
      })
    }

  },
  async getDetail() {
    //访问量
    var result = await inc("menu", this.data.id, "views", 1)
    var result = await getOne("menu", this.data.id)
    this.setData({
      list: result.data,
      imgs: result.data.images
    })
    //导航标题
    wx.setNavigationBarTitle({
      title: this.data.list.name
    })
  },
  //添加关注
  async addLikes() {
    //如果allow为false   跳出
    if (!this.data.allow) {
      return
    }
    this.data.allow = false; //不允许再次点击
    var result = await add("likes", {
      menuId: this.data.id
    }).catch(err => console.log(err))
    //likes+1操作数据库
    var result = await inc("menu", this.data.id, "likes", 1)
    //允许点击关注
    this.data.allow = true;
    //likes+1
    this.data.list.likes += 1;
    //渲染到页面
    this.setData({
      isLike: true,
      list: this.data.list
    })
  },
  //取消关注
  cancelLikes() {
    //如果allow为false   跳出
    if (!this.data.allow) {
      return
    }
    this.data.allow = false; //不允许再次点击
    //再缓存中公获取openid
    var openid = wx.getStorageSync("openid")
    //云存储进行删除
    wx.cloud.callFunction({
      name: "cancelLike",
      data: {
        openid: openid,
        menuId: this.data.id
      }
    }).then(async res => {
      var result = await inc("menu", this.data.id, "likes", -1).catch(err => console.log(err))
      //允许点击
      this.data.allow = true;
      //关注-1
      this.data.list.likes += -1;
      //渲染到页面
      this.setData({
        list: this.data.list,
        isLike: false
      })
    })
  },
  //点击图片全屏
  imageClick(e) {
    var id = e.currentTarget.id;
    wx.previewImage({
      urls: this.data.imgs,
      current: id
    })
  }
})